package org.ifdb.persistency.entity;

import java.util.List;

import javax.jdo.Query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.ifdb.persistency.PMF;

import com.google.appengine.api.datastore.Key;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class City {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key    id;

    @Persistent
    private String name;

    @Persistent
    private State  state;

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public Key getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public static final boolean exists(String cityName){
        City c = new City();
        c.setName(cityName);
        return City.exists(c);
    }
    
    
    @SuppressWarnings("unchecked")
    public static final boolean exists(City city){
        boolean exists = false;
        Query query = null ;
        try { 
             query = PMF.get().getPersistenceManager().newQuery(City.class);     
             query.setFilter("name == cityName");      
             query.declareParameters("String cityName"); 
        } catch(Exception e){}
          try {         
              List<City> results = (List<City>) query.execute(city.getName());         
              if (results.iterator().hasNext()) {
                  for (City c : results) {
                      c.getId();
                      exists = true;
                      break;
                  }
              } else {             
                  exists = false;
              }     
          } finally {        
          
              query.closeAll();     
          }
        return exists;
        
    }


}
